package com.xhai.common.generator;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.xhai.common.config.LocalDataSourceConfig;

import java.sql.Types;
import java.util.Collections;
import java.util.List;

/**
 * @author xhai
 * @description Mybatis的代码生成器
 * @date 2025/5/23
 */
public class MybatisGenerator {

    private static String module = "admin";

    public static void main(String[] args) {
        LocalDataSourceConfig dataSourceConfig = new LocalDataSourceConfig();

        switch (module) {
            case "admin": {
                dataSourceConfig.setDataType("mysql");
                dataSourceConfig.setIp("localhost");
                dataSourceConfig.setPort("3306");
                dataSourceConfig.setDatabase("sys_admin");
                dataSourceConfig.setUsername("root");
                dataSourceConfig.setPassword("root");
            }
        }

        String url = "jdbc:" + dataSourceConfig.getDataType() + "://" + dataSourceConfig.getIp() + ":" + dataSourceConfig.getPort() + "/" + dataSourceConfig.getDatabase();
        String username = dataSourceConfig.getUsername();
        String password = dataSourceConfig.getPassword();
        String author = "songhai";
        String javaOutputDir = "src/main/java";
        String xmlOutputDir = "src/main/resource/mapper";
        String parentPackage = "com.xhai";

        String entityParent = "com.xhai.common.BaseEntity";
        List<String> entityParentColumns = List.of("STATUS", "CREATE_TIME", "CREATE_USERNAME", "UPDATE_TIME", "UPDATE_USERNAME", "LOGIC_DEL_FLAG", "VERSION");
        String entityLogicDelFlag = "LOGIC_DEL_FLAG";
        String entityVersion = "VERSION";

        switch (dataSourceConfig.getDataType()) {
            case "mysql":
                url += "?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&remarks=true&useInformationSchema=true";
                break;
            default:
                break;
        }

        FastAutoGenerator.create(url, username, password)
                .dataSourceConfig(builder ->
                                builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                                            if (typeCode == Types.SMALLINT) {
                                                // 自定义类型转换
                                                return DbColumnType.INTEGER;
                                            }
                                            return typeRegistry.getColumnType(metaInfo);
                                        })
//                                .keyWordsHandler(new MySqlKeyWordsHandler())
                                        .build()
                )
                .globalConfig(builder ->
                                builder.author(author) // 设置作者
//                            .enableSwagger() // 开启 swagger 模式
                                        .enableSpringdoc()
                                        .outputDir(javaOutputDir)
                                        .commentDate("yyyy-MM-dd") // 指定输出目录
                )
                .packageConfig(builder ->
                        builder.parent(parentPackage) // 设置父包名
                                .entity("domain.entity")
                                .mapper("mapper")
                                .service("service")
                                .serviceImpl("service.impl")
                                .controller("controller")
                                .xml("mapper")
                                .pathInfo(Collections.singletonMap(OutputFile.xml, xmlOutputDir)) // 设置mapperXml生成路径
                )
                .strategyConfig(builder ->
//                                builder.addInclude("^sys_.*") // 设置需要生成的表名
                                builder.addInclude("sys_config") // 设置需要生成的表名
//                                .addTablePrefix("sys_") // 设置过滤表前缀
                                        .enableCapitalMode()
                                        // 实体配置策略
                                        .entityBuilder()
                                        .superClass(entityParent)
                                        .addSuperEntityColumns(entityParentColumns)
//                                .addIgnoreColumns(entityParentColumns)
                                        .enableLombok() // 启用 Lombok
                                        .enableTableFieldAnnotation() // 启用字段注解
                                        .versionColumnName(entityVersion)
                                        .logicDeleteColumnName(entityLogicDelFlag)
                                        .naming(NamingStrategy.underline_to_camel)
                                        .columnNaming(NamingStrategy.underline_to_camel)
                                        .idType(IdType.ASSIGN_ID)
                                        // controller配置策略
                                        .controllerBuilder()
//                                .enableHyphenStyle()
                                        .enableRestStyle() // 启用 REST 风格
                                        // mapper配置策略
                                        .mapperBuilder()
                                        .enableMapperAnnotation()
                                        .enableBaseResultMap()
                                        .enableBaseColumnList()
                                        // service配置策略
                                        .serviceBuilder()
                                        .formatServiceFileName("%sService")
                )
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }
}
